package com.handler;

import com.message.GroupChatReqMessage;
import com.message.resp.GroupChatResp;
import com.session.ChatServerContextFactory;
import com.session.GroupChatServerFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.Map;
import java.util.Set;

/**
 * 群聊消息转发处理器
 */
@ChannelHandler.Sharable
public class GroupChatDispatchHandler extends SimpleChannelInboundHandler<GroupChatReqMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupChatReqMessage msg) throws Exception {

//        获取所有组员的名字
        Set<String> groupMembers = GroupChatServerFactory.getInstance().getGroupMembersByGroupName(msg.getGroupName());

//        根据组员的名字获取组员各自的channel
        Map<String, Channel> userNameMappingChannelMap = ChatServerContextFactory.getInstance().getUserNameMappingChannelMapByBatchUserNames(groupMembers);

//        删除哪些已经在 ChatServerContext 中断开连接的组员
        groupMembers.retainAll(userNameMappingChannelMap.keySet());

//        构建群聊消息
        GroupChatResp groupChatResp = new GroupChatResp(ChatServerContextFactory.getInstance().getUserNameByChannel(ctx.channel()), msg.getContent(), msg.getGroupName());

//        向每一个组员发送群聊消息
        userNameMappingChannelMap.forEach((String userName,Channel channel)->{
            channel.writeAndFlush(groupChatResp);
        });
    }
}
